<?php

namespace app\api\controller;
use app\common\controller\Api;
use think\Validate;
use think\Loader;
use think\Page;
use think\Db;
use app\api\model\Cart;
use app\manystore\model\Order as Orders;
use addons\epay\library\Service;

class Order extends Api
{ 
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $user_id = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new Orders;
    }

    /**
     * [cartPay 購物車下單]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-16T23:45:16+0800
     * @return     [type]                   [description]
     */
    public function cartPay()
    {
        // 是否全選，1是0否
        $select_type = $this->request->post("select_type", '1');
        $cart_ids = $this->request->post("cart_ids", '');
        $address_id = $this->request->post("address_id", 0);
        if ( !$select_type && !$cart_ids ) {
            $this->error('請選擇一項商品');
        }

        $address_info = db('user_address')->where(['user_id'=>$this->user_id,'id'=>$address_id])->find();
        if ( !$address_info ) {
            $this->error('未找到該地址');
        }

        $gmodel = new Cart();
        $order = $gmodel->getList($this->user_id,$cart_ids);
        // 有錯誤不給下單
        if ( $order['has_error'] ) {
            $this->error($order['error_msg']);
        }

        if ( !$order['order_total_num'] ) {
            $this->error('購物車為空');
        }

        if ( $this->auth->score < $order['orderTotalIntegral'] ) {
            $this->error('積分不足,去充值',[],203);
        }


        $order_return = $this->model->order_add($this->user_id, $order,$address_info,10);

        // 创建订单
        if ( !$order_return['status'] ) {
            $this->error($this->model->getError() ?: '操作失敗');
        }

        $cart_where = [];
        if ( !$select_type && $cart_ids  ) {
            $cart_where = ['id'=>['in',$cart_ids]];
        }
        // 清空购物车
        $gmodel->clearAll($this->user_id,$cart_where);

        $this->success('操作成功',$order_return['data']);

    }

    /**
     * [buyNowPay 立即購買]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-16T23:45:47+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function buyNowPay($value='')
    {
        $goods_id = $this->request->post('goods_id',0);
        $goods_num = $this->request->post('goods_num',1);
        $goods_sku_id = $this->request->post('goods_sku_id','');

        $address_id = $this->request->post("address_id", 0);

        $address_info = db('user_address')->where(['user_id'=>$this->user_id,'id'=>$address_id])->find();
        if ( !$address_info ) {
            $this->error('未找到該地址');
        }

        $order = $this->model->getBuyNow($this->user_id, $goods_id, $goods_num, $goods_sku_id);
        if ($this->model->hasError()) {
            return $this->error($this->model->getError());
        }

        if ( $this->auth->score < $order['orderTotalIntegral'] ) {
            $this->error('積分不足,去充值',[],203);
        }

        $order_return = $this->model->order_add($this->user_id, $order,$address_info,10);

        // 创建订单
        if ( !$order_return['status'] ) {
            $this->error($this->model->getError() ?: '操作失敗');
        }

        $this->success('操作成功',$order_return['data']);

    }

    /**
     * [integralExchange 積分兌換]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-16T23:46:31+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function integralExchange($value='')
    {
        $goods_id = $this->request->post('goods_id',0);
        $goods_num = $this->request->post('goods_num',1);
        $goods_sku_id = $this->request->post('goods_sku_id','');

        $address_id = $this->request->post("address_id", 0);

        $address_info = db('user_address')->where(['user_id'=>$this->user_id,'id'=>$address_id])->find();
        if ( !$address_info ) {
            $this->error('未找到該地址');
        }

        $order = $this->model->getBuyNow($this->user_id, $goods_id, $goods_num, $goods_sku_id);
        if ($this->model->hasError()) {
            return $this->error($this->model->getError());
        }

        if ( $order['order_pay_price'] >0 || $order['orderTotalIntegral'] == 0 ) {
            return $this->error('請選擇積分商品');
        }

        if ( $this->auth->score < $order['orderTotalIntegral'] ) {
            $this->error('積分不足,去充值',[],203);
        }

        $order_return = $this->model->order_add($this->user_id, $order,$address_info,20);

        // 创建订单
        if ( !$order_return['status'] ) {
            $this->error($this->model->getError() ?: '操作失敗');
        }

        $this->success('操作成功',$order_return['data']);
    }

    /**
     * [getOrderList 獲取訂單列表]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-17T18:02:51+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getOrderList($value='')
    {
        // 订单状态:10=10待付款,20=待发货,30=待收货,40已完成,50已取消(積分訂單不需要用到10，50)
        $order_status = $this->request->post("order_status", 0);
        // 訂單類型:10=商城訂單,20=積分訂單
        $order_type = $this->request->post("order_type", '20');

        $where = ['o.user_id'=>$this->user_id,'o.order_type'=>$order_type];

        if ( $order_status ) {
            $where['o.order_status'] = $order_status;
        }

        $data = $this->model->getOrderList($where,'o.id,o.order_no,o.shop_id,s.name as shop_name,s.logo,o.order_type,o.order_status,total_price,total_integral,delivery_price,pay_price,pay_status,paytime,freight_status,freighttime,receipt_status,receipttime,o.refund_status,o.comment_status,o.name,o.mobile,o.address,o.region_type,o.createtime');

        $this->success('請求成功',$data);
    }

    /**
     * [getOrderInfo 獲取訂單詳情]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-17T19:42:27+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getOrderInfo($value='')
    {
        $rq_data = $this->request->param();
        $validate = Loader::validate('Order');
        if (!$validate->scene('getorderinfo')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $where = ['o.user_id'=>$this->user_id,'o.id'=>$rq_data['order_id']];

        $data = $this->model->getOrderInfo($where,'o.id,o.order_no,o.shop_id,s.name as shop_name,s.logo,o.order_type,o.order_status,total_price,total_integral,delivery_price,pay_price,pay_status,paytime,freight_status,freighttime,receipt_status,receipttime,o.refund_status,o.comment_status,o.name,o.mobile,o.address,o.region_type,o.createtime,o.expressname,o.express,o.expresssn');

        $this->success('請求成功',$data);
    }

    /**
     * [confirmReceipt 確認收貨]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-17T20:18:50+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function confirmReceipt($value='')
    {
        $rq_data = $this->request->param();
        $validate = Loader::validate('Order');
        if (!$validate->scene('getorderinfo')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $where = ['o.user_id'=>$this->user_id,'o.id'=>$rq_data['order_id']];

        $time = time();
        $data = $this->model->getOrderInfo($where,'o.id,o.order_no,o.shop_id,s.name as shop_name,s.logo,o.order_type,o.order_status,total_price,total_integral,delivery_price,pay_price,pay_status,paytime,freight_status,freighttime,receipt_status,receipttime,o.refund_status,o.comment_status,o.name,o.mobile,o.address,o.region_type,o.createtime,o.expressname,o.express,o.expresssn');
        if ( !$data ) {
            $this->error('未找到該訂單');
        }

        if ( $data['order_status'] != '30' ) {
            $this->error('訂單狀態有誤');
        }

        if ( $data['refund_status'] == '20' ) {
            $this->error('已提交退款申請,請耐心等待商家處理');
        }

        $status = $this->model
                    ->where(['id'=>$rq_data['order_id']])
                    ->update(['order_status'=>'40','receipt_status'=>'20','receipttime'=>$time]);

        if ( !$status ) {
            $this->error('操作失敗');
        }
        addShopMoney($data['shop_id'],$data['pay_price'],'確認訂單',$data['order_no'],$time);
        $this->success('操作成功');
    }

    /**
     * [publishComment 發表評論]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-17T20:34:36+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function publishComment($value='')
    {
        // $params = $this->request->post("row/a");

        $params = file_get_contents("php://input");

        if ( !$params ) {
            $this->error('未找到該訂單');
        }
        $params = json_decode($params,true);
        $order_id = isset($params['order_id'])?$params['order_id']:0;
        if ( !$order_id ) {
            $this->error('未找到該訂單');
        }

        if ( !isset($params['goods']) ) {
            $this->error('請提交評論');
        }

        $comment = $params['goods'];
        // if ( !$comment ) {
        //     $this->error('請提交評論');
        // }

        // $rq_data = $this->request->param();
        // $validate = Loader::validate('Order');
        // if (!$validate->scene('publishcomment')->check($rq_data)) {
        //     $this->error($validate->getError());
        // }

        $where = ['o.user_id'=>$this->user_id,'o.id'=>$order_id];

        $data = $this->model->getOrderInfo($where,'o.id,o.order_no,o.shop_id,s.name as shop_name,s.logo,o.order_type,o.order_status,total_price,total_integral,delivery_price,pay_price,pay_status,paytime,freight_status,freighttime,receipt_status,receipttime,o.refund_status,o.comment_status,o.name,o.mobile,o.address,o.region_type,o.createtime,o.expressname,o.express,o.expresssn');
        if ( !$data ) {
            $this->error('未找到該訂單');
        }

        if ( $data['order_status'] != '40' ) {
            $this->error('訂單狀態有誤');
        }

        if ( $data['comment_status'] != '10' ) {
            $this->error('請勿重複評論');
        }


        $time = time();

        Db::startTrans();
        try {
            $status = $this->model
                ->where(['id'=>$order_id])
                ->update(['comment_status'=>'20']);

            if ( !$status ) {
                Db::rollback();
                $this->error('操作失敗');
            }

            foreach ($comment as $key => $value) {
                $order_goods_info = db('order_goods')->where(['id'=>$value['order_goods_id']])->find();
                if ( !$order_goods_info ) {
                    continue;
                }
                $order_comment_arr = [];
                $order_comment_arr['goods_id'] = $order_goods_info['goods_id'];
                $order_comment_arr['order_id'] = $order_id;
                $order_comment_arr['user_id'] = $this->user_id;
                $order_comment_arr['content'] = $value['content'];
                $order_comment_arr['ip'] = request()->ip();;
                $order_comment_arr['goods_rank'] = $value['goods_rank'];
                $order_comment_arr['createtime'] = $time;
                $order_comment_arr['updatetime'] = $time;
                $order_comment_arr['goods_attr'] = $order_goods_info['goods_attr'];
                $order_comment_arr['order_goods_id'] = $value['order_goods_id'];

                $status = db('comment')->insertGetId($order_comment_arr);
                if ( !$status ) {
                    Db::rollback();
                    $this->error('操作失敗');
                }
                if ( isset($value['images']) && $value['images'] ) {
                    $images_arr_buf = explode(',', $value['images']);
                    $images_arr = [];
                    foreach ($images_arr_buf as $ki => $vi) {
                        $images_arr[] = ['images'=>$vi,'type'=>'4','relation_id'=>$status];
                    }
                    db('upload_images')->insertAll($images_arr);
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('操作失敗'.$e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * [refund 申請退款]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-17T22:39:44+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function refund($value='')
    {
        $rq_data = $this->request->param();
        $validate = Loader::validate('Order');
        if (!$validate->scene('refund')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $where = ['o.user_id'=>$this->user_id,'o.id'=>$rq_data['order_id']];

        $data = $this->model->getOrderInfo($where,'o.id,o.order_no,o.shop_id,s.name as shop_name,s.logo,o.order_type,o.order_status,total_price,total_integral,delivery_price,pay_price,pay_status,paytime,freight_status,freighttime,receipt_status,receipttime,o.refund_status,o.comment_status,o.name,o.mobile,o.address,o.region_type,o.createtime,o.expressname,o.express,o.expresssn');
        if ( !$data ) {
            $this->error('未找到該訂單');
        }
        if ( $data['order_type'] == '20' ) {
            $this->error('積分訂單不可申請退款');
        }

        if ( !in_array($data['order_status'], ['20','30']) ) {
            $this->error('訂單狀態有誤');
        }

        if ( $data['refund_status'] == '20' ) {
            $this->error('已申請退款,請耐心等待商家處理');
        }

        $time = time();

        Db::startTrans();
        try {
            $status = $this->model
                ->where(['id'=>$rq_data['order_id']])
                ->update(['refund_status'=>'20']);

            if ( !$status ) {
                Db::rollback();
                $this->error('操作失敗');
            }

            $order_refund_arr = [];
            $order_refund_arr['order_id'] = $rq_data['order_id'];
            $order_refund_arr['user_id'] = $this->user_id;
            $order_refund_arr['refund_reason'] = $rq_data['refund_reason'];
            $order_refund_arr['refund_content'] = $rq_data['refund_content'];
            $order_refund_arr['createtime'] = $time;
            $order_refund_arr['updatetime'] = $time;

            $status = db('order_refund')->insertGetId($order_refund_arr);
            if ( !$status ) {
                Db::rollback();
                $this->error('操作失敗');
            }
            if ( isset($rq_data['images']) && $rq_data['images'] ) {
                $images_arr_buf = explode(',', $rq_data['images']);
                $images_arr = [];
                foreach ($images_arr_buf as $key => $value) {
                    $images_arr[] = ['images'=>$value,'type'=>'5','relation_id'=>$status];
                }
                db('upload_images')->insertAll($images_arr);
            }
            $this->model->where(['id'=>$rq_data['order_id']])->update(['refund_id'=>$status]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('操作失敗');
        }
        $this->success('操作成功');
    }

    /**
     * [cancel 取消訂單]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-17T23:04:48+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function cancel($value='')
    {
        $rq_data = $this->request->param();
        $validate = Loader::validate('Order');
        if (!$validate->scene('getorderinfo')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $where = ['o.user_id'=>$this->user_id,'o.id'=>$rq_data['order_id']];

        $data = $this->model->getOrderInfo($where,'o.id,o.order_no,o.shop_id,s.name as shop_name,s.logo,o.order_type,o.order_status,total_price,total_integral,delivery_price,pay_price,pay_status,paytime,freight_status,freighttime,receipt_status,receipttime,o.refund_status,o.comment_status,o.name,o.mobile,o.address,o.region_type,o.createtime,o.expressname,o.express,o.expresssn');
        if ( !$data ) {
            $this->error('未找到該訂單');
        }

        if ( $data['order_status'] != '10' ) {
            $this->error('訂單狀態有誤');
        }

        $status = $this->model
                    ->where(['id'=>$rq_data['order_id']])
                    ->update(['order_status'=>'50','canceltime'=>time()]);

        if ( !$status ) {
            $this->error('操作失敗');
        }
        $this->success('操作成功');
    }

    /**
     * [getConsumptionRecord 獲取金額消費記錄]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-11-02T17:30:48+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getConsumptionRecord($value='')
    {
        $subQuery = "(
                SELECT
                  c.id,c.order_no,c.payment_amount as pay_price,c.paytime,10 AS order_status,c.createtime, 1 AS type
                FROM
                  ".config('database.prefix')."recharge as c  WHERE (c.user_id = ".$this->auth->id." and c.pay_status = '20' and c.payment_amount > 0)
                UNION
                  SELECT
                    o.id,o.order_no,o.pay_price,o.paytime,o.order_status,o.createtime, 2 AS type
                  FROM
                    ".config('database.prefix')."order as o  WHERE (o.user_id = ".$this->auth->id." and o.pay_status = '20' and o.pay_price > 0)
                        )";
        $total = Db::table($subQuery.' a')
            ->count();

        $page = new Page($total,10);

        $list = Db::table($subQuery.' a')
            ->limit($page->firstRow.','.$page->listRows)
            ->order('createtime','desc')
            ->select();

        foreach ($list as $key => &$value) {
            if ( $value['order_status'] == '50' ) {
                $value['order_status'] = '20';
            }elseif ( in_array($value['order_status'], ['20','30','40']) ) {
                $value['order_status'] = '10';
                $value['pay_price'] = - $value['pay_price'];
            }
        }
        unset($value);

        $data = ['total'=>$total,'listrows'=>$page->listRows,'totalpages'=>$page->totalPages,'data'=>$list];

        $this->success('請求成功',$data);
    }

    /**
     * [reGetCode 微信支付]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-11-02T18:13:50+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function reGetCode($value='')
    {
        $rq_data = $this->request->param();
        $validate = Loader::validate('Order');
        if (!$validate->scene('regetcode')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $openid = db('third')->where(['user_id'=>$this->auth->id,'apptype'=>'miniapp'])->value('openid');
        if ( !$openid ) {
            $this->error('系統繁忙');
        }

        $order_no = $rq_data['order_no'];

        // 充值订单
        if(strpos($order_no,'JF') !== false){
            $order = db('recharge')->where(['user_id'=>$this->auth->id,'pay_status'=>'10','order_no'=>$order_no])->find();
            if ( !$order ) {
                $this->error('未找到該訂單');
            }
            $order['pay_price'] = $order['payment_amount'];
            $body = '在線充值';
            $pay_price = $order['pay_price'];
        }else{
            $user_id = $this->auth->id;
            $count = db('order')
                ->where(['user_id'=>$user_id,'order_status'=>'10','pay_status'=>'10','order_no'=>$order_no])
                ->whereOr(function ($query) use($user_id,$order_no) {
                    $query->where(['user_id'=>$user_id,'order_status'=>'10','parent_order_no'=>$order_no]);
                })
                ->count();
            if ( !$count ) {
                $this->error('未找到該訂單');
            }

            if ( $count == 1 ) {
                $order = db('order')->where(['user_id'=>$this->auth->id,'order_status'=>'10','pay_status'=>'10','order_no'=>$order_no])->find();
                if ( !$order ) {
                    $this->error('未找到該訂單');
                }
                $pay_price = $order['pay_price'];
            }else{
                $pay_price = db('order')
                ->where(['user_id'=>$user_id,'order_status'=>'10','pay_status'=>'10','order_no'=>$order_no])
                ->whereOr(function ($query) use($user_id,$order_no) {
                    $query->where(['user_id'=>$user_id,'order_status'=>'10','parent_order_no'=>$order_no]);
                })
                ->sum('pay_price');
            }

            $body = '支付訂單';
            if ( $pay_price < 0.01 ) {
                orderPaySuccess($order_no);
                $this->success('支付成功',[],206);
            }
        }

        $orderDate = [];
        $orderDate['out_trade_no'] = $order_no;
        $orderDate['body'] = $body;
        $orderDate['openid'] = $openid;
        $orderDate['method'] = 'miniapp';
        $orderDate['orderid'] = $order_no;
        $orderDate['amount'] = $pay_price;
        $orderDate['type'] = 'wechat';
        $Service = new Service;
        $code = $Service->submitOrder($orderDate);
        if ( $code['code'] != 200 ) {
            $this->error('請求失敗');
        }
        $code = $code['data'];
        $this->success('請求成功',$code);
    }
}